import { ListContext, ListContextProps } from ".";
import { computed, defineComponent, inject } from "vue";

export interface ListItemProps {
    id: string | number,
    data?: any,
    actions?: any,
    avatar?: any,
    content?: any,
    title?: any,
    desc?: any,
    activeKey?: any
}

export default defineComponent({
    name: 'ListItem',
    props: ['id', 'data', 'actions', 'avatar', 'content', 'title', 'desc', 'activeKey'],
    setup (props: ListItemProps, { slots, emit }) {
        const ctx: ListContextProps|undefined = inject(ListContext);
        const setActiveKey = ctx.setActiveKey;

        const classList = computed(() => ({
            'cm-list-item': true,
            'cm-list-item-active': ctx.activeKey.value === props.id
        }));

        const onClick = () => {
            if (ctx?.selectable) {
                setActiveKey && setActiveKey(props.id);
                ctx.onSelect?.(props.data);
            }
        };

        return () => <div class={classList.value} onClick={onClick}>
            <div class="cm-list-item-main">
                <div class="cm-list-item-meta">
                    {props.avatar ? <div class="cm-list-item-avatar">{props.avatar}</div> : null}
                    {props.title || props.desc ? <div class="cm-list-item-body">
                        <div class="cm-list-item-title">{props.title}</div>
                        <div class="cm-list-item-desc">{props.desc}</div>
                    </div> : null}
                </div>
                <div class="cm-list-item-content">
                    {slots.default && slots.default()}
                </div>
            </div>
            {
                props.actions
                    ? <ul class="cm-list-item-addon">
                        {props.actions}
                    </ul>
                    : null
            }
        </div>;
    }
});
